package com.zhentao.service.impl;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zhentao.exception.ZhentaoException;
import com.zhentao.helper.MenuHelper;
import com.zhentao.model.entity.system.SysMenu;
import com.zhentao.model.entity.system.SysUser;
import com.zhentao.model.vo.common.ResultCodeEnum;
import com.zhentao.model.vo.system.SysMenuVo;
import com.zhentao.service.SysMenuService;
import com.zhentao.mapper.SysMenuMapper;
import com.zhentao.util.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.sql.Wrapper;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 86131
 * @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
 * @createDate 2024-08-19 14:42:07
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    //    查询菜单
    @Override
    public List<SysMenu> findNodes() {

        List<SysMenu> sysMenuList = sysMenuMapper.selectAll();
//        判断是否为空

        if (sysMenuList == null) {
            return null;
        }

        List<SysMenu> treeList = MenuHelper.buildTree(sysMenuList);
        return treeList;
    }

    //    添加菜单
    @Override
    public void saveMenu(SysMenu sysMenu) {
        sysMenuMapper.saveMenu(sysMenu);
    }

    //    修改菜单
    @Override
    public void updateMenuById(SysMenu sysMenu) {
        sysMenuMapper.updateMenuById(sysMenu);
    }

    //    删除菜单
    @Override
    public void removeMenuById(Integer id) {
        int count = sysMenuMapper.countByParentId(id);  // 先查询是否存在子菜单，如果存在不允许进行删除
        if (count > 0) {
            throw new ZhentaoException(ResultCodeEnum.NODE_ERROR);
        }

        sysMenuMapper.removeMenuById(id);
    }

    //    动态菜单
    @Override
    public List<SysMenuVo> findUserMenuList() {
        SysUser sysUser = AuthContextUtil.get();
        Long userId = Long.valueOf(sysUser.getId());
        // 获取当前登录用户的id
        List<SysMenu> sysMenuList = sysMenuMapper.selectListByUserId(userId);

        //构建树形数据
        List<SysMenu> sysMenuTreeList = MenuHelper.buildTree(sysMenuList);
        return this.buildMenus(sysMenuTreeList);
    }

    // 将List<SysMenu>对象转换成List<SysMenuVo>对象
    private List<SysMenuVo> buildMenus(List<SysMenu> menus) {

        List<SysMenuVo> sysMenuVoList = new LinkedList<SysMenuVo>();
        for (SysMenu sysMenu : menus) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setTitle(sysMenu.getTitle());
            sysMenuVo.setName(sysMenu.getComponent());
            List<SysMenu> children = sysMenu.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                sysMenuVo.setChildren(buildMenus(children));
            }
            sysMenuVoList.add(sysMenuVo);
        }
        return sysMenuVoList;
    }
}




